package cn.tedu.work.controller;

import cn.tedu.work.entity.User;
import cn.tedu.work.utils.DBUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Controller
public class Usercontroller {
    @RequestMapping("/reg1")
    @ResponseBody
  public String reg(User user){
        try(Connection conn=DBUtils.getConn()) {
            System.out.println("user = " + user);
            String sql ="insert into user values(null,?,?,?,?)";
            PreparedStatement ps =conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ps.setString(2,user.getPassword());
            ps.setString(3,user.getNick());
            ps.setInt(4,user.getAge());
            ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "注册成功！";
    }
    @RequestMapping("/login1")
    @ResponseBody
    public String login(User user){
        try (Connection conn =DBUtils.getConn()){
            System.out.println("user = " + user);
            String sql ="select password from user where username=?";
            PreparedStatement ps =conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ResultSet rs =ps.executeQuery();
            if (rs.next()){
                String password =rs.getString(1);
                if (password.equals(user.getPassword())){
                    return "登录成功！";
                }else{
                    return "密码错误";
                }
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "用户不存在！";
    }
}
